﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NRCP.BusinessLogicLayer;
using NRCP.Helpers;
using NRCP.BusinessEntities;
using Imgalib.Utility;

namespace NRCP
{
    public partial class National_Plan : NationalPlanBase
    {
        private Int32 TotalFishTypes
        {
            get
            {
                try
                {
                    return Convert.ToInt32(ViewState["TotalFishTypes"].ToString());
                }
                catch
                {
                    return 0;
                }
            }
            set
            {
                ViewState["TotalFishTypes"] = value;
            }
        }

        private List<Int32> SampleInput
        {
            get
            {
                return Enumerable.Repeat(0, TotalFishTypes).ToList<Int32>();
                
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.PresentPageStep = NationalPlanSteps.YearlyPlan;
                this.CheckSteps();

                respMessage.SetNoticeMessage(@" Note: <span class='validation-message'>*</span> indicates required");
                LoadData();
            }

        }

        private void LoadData()
        {
            NationalPlanDivisionBLL bll = new NationalPlanDivisionBLL();
            repDivision.DataSource = bll.GetNationalPlanDivisionsByNationalPlanId(SiteUtility.IntQueryParam);          
            repDivision.DataBind();

            
        }

        protected void repTestGroups_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater repSampleCount = e.Item.FindControl("repSampleCount") as Repeater;
                if (repSampleCount != null)
                {
                    repSampleCount.DataSource = SampleInput;
                    repSampleCount.DataBind();
                }
            }
            
        }

        protected void repDivision_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Repeater repFishTypes = e.Item.FindControl("repFishTypes") as Repeater;
                if (repFishTypes != null)
                {
                    NationalPlanFishBLL nationalPlanFishBll = new NationalPlanFishBLL();
                    List<NationalPlanFish> fishTypes = nationalPlanFishBll.GetNationalPlanFishByNationalPlanId(SiteUtility.IntQueryParam);
                    repFishTypes.DataSource = fishTypes;
                    repFishTypes.DataBind();
                    TotalFishTypes = fishTypes.Count;
                }

                Repeater repTestGroups = e.Item.FindControl("repTestGroups") as Repeater;
                if (repTestGroups != null)
                {
                    NationalPlanChemicalGroupBLL nationalPlanGroupBll = new NationalPlanChemicalGroupBLL();
                    repTestGroups.DataSource = nationalPlanGroupBll.GetNationalPlanChemicalGroupsByNationalPlanlId(SiteUtility.IntQueryParam);
                    repTestGroups.DataBind();
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            List<Int32> yearlyPlanIds = new List<int>();
            try
            {
                List<int> fishIdList = new List<int>();
                foreach (RepeaterItem item in repDivision.Items)
                {
                    Int32 divisionId = GetIdentityKey(item, "hidDivisionId", true); //divisionId
                    Repeater repFishTypes = item.FindControl("repFishTypes") as Repeater;
                    if (repFishTypes != null)
                    {
                        foreach (RepeaterItem fishItem in repFishTypes.Items)
                        {
                            fishIdList.Add(GetIdentityKey(fishItem, "hidFishId", true));
                        }
                    }

                    Repeater repTestGroups = item.FindControl("repTestGroups") as Repeater;
                    if (repTestGroups != null)
                    {
                        foreach (RepeaterItem testItem in repTestGroups.Items)
                        {
                            Int32 testGroupId = GetIdentityKey(testItem, "hidTestGroupId", true); //Test Group Id
                            Repeater repSampleCount = testItem.FindControl("repSampleCount") as Repeater;
                            if (repSampleCount != null)
                            {
                                foreach (RepeaterItem sampleCountItem in repSampleCount.Items)
                                {
                                    int fishId = fishIdList[sampleCountItem.ItemIndex]; //fish id
                                    int sampleCount = GetIdentityKey(sampleCountItem, "txtSample", false); //sample count
                                    int yearlyPlanId=SaveYearlyNationalPlan(testGroupId, divisionId, fishId, sampleCount);
                                    if (yearlyPlanId > 0)
                                    {
                                        yearlyPlanIds.Add(yearlyPlanId);
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                NationalPlanBLL nationalPlanBll = new NationalPlanBLL();
                                NationalPlan nationalPlan=nationalPlanBll.GetNationalPlanById(SiteUtility.IntQueryParam);
                                nationalPlan.CompletedSteps = CompletedSteps.YearlyPlan.ToString();
                                nationalPlanBll.UpdateNationalPlan(nationalPlan);
                            }
                        }
                    }
                }
                HttpContext.Current.Response.Redirect(SiteSettings.BaseUrl + "zonal-plan.aspx?params=" + Cryptography.Encrypt(SiteUtility.IntQueryParam.ToString()));
            }
            catch(Exception ex)
            {
                respMessage.SetFailMessage("Failed to Save Plan."+ex.InnerException.Message);
                NationalPlanDetailsYearlyBLL yearlyPlanbll = new NationalPlanDetailsYearlyBLL();
                if (yearlyPlanIds.Count > 0)
                {
                    yearlyPlanbll.DeleteNationalPlanDetailsYearlies(yearlyPlanIds);
                }
            }
        }

        private Int32 GetIdentityKey(RepeaterItem item,String controlName,bool isHiddenField)
        {
            if (isHiddenField)
            {
                HiddenField hidId = item.FindControl(controlName) as HiddenField;
                return Convert.ToInt32(hidId.Value.Trim()); 
            }
            else
            {
                TextBox hidId = item.FindControl(controlName) as TextBox;
                return Convert.ToInt32(hidId.Text.Trim()); 
            }
        }
        private Int32 SaveYearlyNationalPlan(int testGroupId, int divisionId, int fishId, int samplecount)
        {
            NationalPlanDetailsYearlyBLL yearlyPlanbll = new NationalPlanDetailsYearlyBLL();
            NationalPlanDetailsYearly yearlyPlan = new NationalPlanDetailsYearly();
            yearlyPlan.ChemicalGroupId = testGroupId;
            yearlyPlan.DivisionId = divisionId;
            yearlyPlan.FishId = fishId;
            yearlyPlan.NationalPlanId = SiteUtility.IntQueryParam;
            yearlyPlan.Count = samplecount;
            yearlyPlan.Status = PlanStatus.Pending.ToString();
            return yearlyPlanbll.CreateNewNationalPlanDetailsYearly(yearlyPlan);
        }
    }
}